import { Component } from 'react'
import {
  Table, Button, Popconfirm, message, Input
} from 'antd'
import AddProduct from '../components/AddProduct'
import EditProduct from '../components/EditProduct'
import request, { baseURL } from '../api/request'

import 'antd/dist/antd.css'
import './GoodsList.css'

const { Search } = Input

export default class GoodsList extends Component {
  state = {
    products: [], // 商品列表
    product: {}, // 当前编辑的商品
    total: 0, // 商品总数
    pageSize: 3, // 每页的商品数
    page: 1, // 当前页码
    search: '', // 搜索框的内容
    addProductDialogVisible: false, // 显示添加商品对话框
    editProductDialogVisible: false, // 显示编辑商品对话框
  }

  // 获取商品列表
  getTableData = async () => {
    let { page, pageSize, search } = this.state
    const { data } = await request.get('/products', {
      params: {
        page, pageSize, search
      }
    })
    this.setState({
      products: data.products,
      total: data.total
    })
  }

  // 删除一件商品
  handleDelete = async id => {
    const { data } = await request.delete('/products', { data: { id }})
    if (data.code === 200) {
      message.info('删除成功')
      // 删除最后一页的唯一数据时, 回到上一页
      this.setState(
        state => {
          const totalPages = Math.ceil(state.total / state.pageSize)
          let page = state.page
          if (page > 1 && page === totalPages
            && state.total % state.pageSize === 1) {
            page--
          }
          return { page }
        },
        this.getTableData
      )
    } else {
      message.error('删除失败')
    }
  }

  // 分页
  changePage = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getTableData()
    })
  }

  // 搜索
  onSearch = search => {
    this.setState({ page: 1, search }, this.getTableData)
  }

  // 显示/隐藏添加商品对话框
  toggleAddProductDialog = () => {
    this.setState(state => ({
      addProductDialogVisible: !state.addProductDialogVisible
    }))
  }

  // 显示/隐藏编辑商品对话框
  toggleEditProductDialog = async id => {
    if (Number.isInteger(id)) {
      const { data } = await request.get('/product', { params: { id } })
      console.log(data)
      this.setState({
        product: data
      })
    }
    this.setState(state => ({
      editProductDialogVisible: !state.editProductDialogVisible
    }))
  }

  componentDidMount () {
    this.getTableData()
  }

  render () {
    const columns = [
      {
        title: '#',
        dataIndex: 'id',
        key: 'id',
      },
      {
        title: '商品名称',
        dataIndex: 'title',
        key: 'title',
      },
      {
        title: '单价',
        dataIndex: 'price',
        key: 'price',
      },
      {
        title: '商品图片',
        dataIndex: 'pic',
        key: 'pic',
        render: src => (
          <img src={baseURL + src}
            alt="" width="64px" height="64px"/>
        )
      },
      {
        title: '操作',
        dataIndex: 'id',
        key: 'id',
        render: id => (
          <div>
            <Popconfirm
              okText="确认删除"
              cancelText="取消"
              title="确定删除该记录?"
              onConfirm={() => {
                this.handleDelete(id)
              }}
            >
              <Button type="danger">删除</Button>
            </Popconfirm>
            <Button className="btnEditProduct"
              onClick={() => this.toggleEditProductDialog(id)}
            >编辑</Button>
          </div>
        )
      },
    ];

    return (
      <div className="GoodsList">
        <div className="header">
          <Search className="search"
            placeholder="search..."
            allowClear
            enterButton="Search"
            size="large"
            onSearch={this.onSearch}
          />
          <Button className="btnAddProduct"
            type="primary"
            onClick={this.toggleAddProductDialog}
          >添加商品</Button>
        </div>
        <Table className="table"
          dataSource={this.state.products}
          columns={columns}
          rowKey="id"
          pagination={{
            pageSize: this.state.pageSize,
            current: this.state.page,
            onChange: this.changePage,
            total: this.state.total
          }}
        />
        <AddProduct
          visible={this.state.addProductDialogVisible}
          onCancel={this.toggleAddProductDialog}
          getTableData={this.getTableData}
        />
        <EditProduct
          visible={this.state.editProductDialogVisible}
          onCancel={this.toggleEditProductDialog}
          getTableData={this.getTableData}
          data={this.state.product}
        />
      </div>
    )
  }
}
